package com.my.dao.impl;

import java.util.List;
import java.util.regex.Pattern;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import com.my.dao.IBaseDao;
import com.my.entity.UserEntity;
import com.my.page.Page;

@SuppressWarnings("rawtypes")
public class BaseDaoImpl extends BasicDAO<UserEntity, Object> implements IBaseDao {
	private Datastore dt;
	protected BaseDaoImpl(Mongo mongo, Morphia morphia, String dbName) {
		super(mongo, morphia, dbName);
		dt = morphia.createDatastore(mongo, dbName);
	}

	/**
	 * 删除全部
	 */
	public void deleteAll(Class clazz) {
		Query query = createQuery(clazz);
		dt.delete(query);
	}
	/**
	 * 根据value删除
	 */
	public void deleteByValue(Class clazz, String title, Object value) {
		Query query = createQuery(clazz, title, value);
		dt.delete(query);
	}
	/**
	 * 查询全部
	 */
	public List findAll(Class clazz) {
		return dt.find(clazz).asList();
	}
	/**
	 * 根据ID查询
	 */
	public List findByID(Class clazz, Object idValue) {
		Query query = createQuery(clazz);
		query.filter("_id", idValue);
		return query.asList();
	}
	/**
	 * 根据value查询
	 */
	public List findByValue(Class clazz, String title, Object value) {
		Query query = createQuery(clazz, title, value);
		query.filter(title, value);
		return query.asList();
	}
	/**
	 * 根据value模糊查询
	 */
	public List findByValueFuzzyQuery(Class clazz, String title, Object value) {
		Query query = createQuery(clazz);
		Pattern pattern = Pattern.compile(value.toString(),Pattern.CASE_INSENSITIVE);
		query.filter(title, pattern);
		return query.asList();
	}
	/**
	 * 分页查询
	 */
	public Query pagingQuery(Class clazz, Page page) {
		Query query = createQuery(clazz);
		if(page != null){
			query.limit(page.getPageSize()).offset((page.getCurrentPageNo() - 1) * page.getPageSize());
			page.setTotal((int)query.countAll());
		}
		return query;
	}
	/**
	 * 存储对象
	 */
	public void saveEntity(Object entity) {
		dt.save(entity);
	}
	/**
	 * 修改对象
	 */
	public void updateEntity(Object entity) {
		dt.save(entity);
	}

	
	
	/**
	 * 创建查询
	 * @param clazz		类模板
	 * @return
	 */
	protected Query createQuery(Class clazz){
		return dt.createQuery(clazz);
	}
	/**
	 * 根据value创建查询
	 * @param clazz		类模板
	 * @param title		字段名
	 * @param value		值
	 * @return
	 */
	protected Query createQuery(Class clazz,String title,Object value){
		return (Query) dt.createQuery(clazz).field(title).equal(value);
	}
}
